// src/utils/request.js
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 创建 axios 实例，不设置 baseURL，因为请求会通过 Vite 的 proxy 配置进行转发
const service = axios.create({
  timeout: 5000,  // 设置超时时间
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    config.headers['Accept'] = 'application/json';
    config.headers['Request-From'] = 'mobile';

    // 添加 Token
    let token = sessionStorage.getItem('token') ? JSON.parse(sessionStorage.getItem('token')).token : null;
    if (token) {
      config.headers['Token'] = token;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.success === true) {
      return res;
    } else {
      return res;
    }
  },
  (error) => {
    if (axios.isCancel(error)) {
      console.log('Request canceled', error.message);
      return Promise.reject(error);
    }

    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
      ElMessage.error('请求超时，请稍后再试！');
      return Promise.reject(error);
    }

    return Promise.reject(error);
  }
);

// 创建一个取消请求的令牌
const cancelToken = axios.CancelToken;
let cancel;

// 统一的请求方法
export const getRequest = (url, params) => {
  const source = cancelToken.source();
  return service.get(url, {
    params,
    cancelToken: source.token,
  });
};

export const postRequest = (url, data) => {
  const source = cancelToken.source();
  return service.post(url, data, {
    cancelToken: source.token,
  });
};

export const uploadFileRequest = (url, formData) => {
  const source = cancelToken.source();
  return service.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    cancelToken: source.token,
  });
};

export const downloadFileRequest = (url) => {
  const source = cancelToken.source();
  return service.get(url, {
    responseType: 'blob',
    cancelToken: source.token,
  });
};

// 取消所有请求的方法
export const cancelAllRequests = () => {
  if (cancel) {
    cancel('取消请求');
    cancel = null;
  }
};

export default service;